package top.starmc.starpet.listener

import eos.moe.dragoncore.api.gui.event.CustomPacketEvent
import eos.moe.dragoncore.network.PacketSender
import org.bukkit.Material
import org.bukkit.entity.Player
import org.bukkit.event.player.PlayerQuitEvent
import org.bukkit.inventory.ItemStack
import taboolib.common.platform.event.SubscribeEvent
import taboolib.platform.util.isAir
import top.starmc.starpet.config.Config
import top.starmc.starpet.util.SlotUtil
import top.starmc.starpet.util.getPlayerData
import top.starmc.starpet.util.isPetItem

object Slots {
    private val saving = HashSet<Player>()

    @SubscribeEvent
    fun onSlotPacket(event: CustomPacketEvent) {
        val player = event.player
        if (event.identifier == "DragonCore_ClickSlot") {
            if (!event.isCancelled && player !in saving) {
                val slot = event.data[0]
                if (slot == Config.equipSlot) {
                    val handItem = player.itemOnCursor
                    if (handItem.isAir() || handItem.isPetItem()) {
                        saving += player
                        with(player.getPlayerData()) {
                            val handler = SlotUtil.handleSlotItem(item, handItem, event.data[1].toInt())
                            if (handler.isModify) {
                                setPet(handler.slotAfter)
                                player.itemOnCursor = handler.handAfter
                            }
                        }
                        saving -= player
                    }
                }
            }
        } else if (event.identifier == "DragonCore_RetrieveSlot") {
            if (!event.isCancelled) {
                val slot = event.data[0]
                if (slot == Config.equipSlot) {
                    with(player.getPlayerData()) {
                        PacketSender.putClientSlotItem(player, Config.equipSlot, item ?: ItemStack(Material.AIR))
                    }
                }
            }
        }
    }

    @SubscribeEvent
    fun onQuit(event: PlayerQuitEvent) {
        saving -= event.player
    }
}